#include "Library.h"
#include <QMutexLocker>
#include <QDebug>

Library::Library(int maxBooksNumber, QObject *parent) :
	QObject(parent), maxBooksNumber(maxBooksNumber), booksNumber(0), freeBooksNumber(0)
{

}

int Library::getFreeBooksNumber()
{
//	qDebug() << "Library::getFreeBooksNumber";
	return freeBooksNumber;
}

int Library::addBook()
{
	QMutexLocker locker(&mutex);
//	qDebug() << "Library::addBook";
	Book *newBook = new Book();
	books.append(newBook);
	freeBooksNumber++;
	emit freeBooksNumberChanged(freeBooksNumber);
	emit freeBook(newBook->getId());
	return newBook->getId();
}

bool Library::hasEmptySlots()
{
//	qDebug() << "Library::hasEmptySlots";
	return booksNumber < maxBooksNumber;
}

int Library::getAnyBook()
{
//	qDebug() << "Library::getAnyBook";
	QMutexLocker locker(&mutex);
	if (freeBooksNumber == 0) {
		return -1;
	}

	int rand = qrand() % freeBooksNumber;
	foreach (Book *book, books) {
		if (book->isFree()) {
			rand--;
			if (rand == 0) {
				freeBooksNumber--;
				book->take();
				emit freeBooksNumberChanged(freeBooksNumber);
				emit readBook(book->getId());
				return book->getId();
			}
		}
	}

	return -1;
}

void Library::returnBook(int bookId)
{
//	qDebug() << "Library::returnBook " << bookId;
	QMutexLocker locker(&mutex);
	books[bookId]->returnToLibrary();
	freeBooksNumber++;
	emit freeBooksNumberChanged(freeBooksNumber);
	emit freeBook(bookId);
	books[bookId]->wakeOne();
}

void Library::reserveSlot()
{
//	qDebug() << "Library::reserveSlot";
	booksNumber++;
}

void Library::getBook(int bookId)
{
//	qDebug() << "Library::getBook " << bookId;
	QMutexLocker locker(&mutex);
	emit deactivate();
	while (!books[bookId]->isFree()) {
		books[bookId]->wait(&mutex);
	}
	emit activate();
	freeBooksNumber--;
	books[bookId]->take();
	emit editBook(bookId);
	emit freeBooksNumberChanged(freeBooksNumber);
}
